const express=require('express');
const pool=require('../util/pool.js');
const r=express.Router();

// http://127.0.0.1:8080/v1/orders/upload
r.post('/upload',(req,res,next)=>{
    let obj=req.body;
    let x,sta=400;
    for(x in obj){
        if(!obj[x]){//x属性名， obj[x]属性值
        res.send({code:sta,msg:x+'不能为空'});
        //阻止往后执行
        return;
        }
        sta++;
    }
    pool.query('insert into xz_order set ?',[obj],(err,results)=>{
        console.log('results: ', results);
        if(err){
            next(err);
            return;
        }
        res.send({code:200,msg:'上传成功！'});
    });
    // res.send({code:200,msg:'上传成功！'});
});

// http://127.0.0.1:8080/v1/orders/update
r.put('/update',(req,res,next)=>{
    let obj=req.body;
    let x,sta=400;
    for(x in obj){
        if(!obj[x]){//x属性名， obj[x]属性值
        res.send({code:sta,msg:x+'不能为空！'});
        //阻止往后执行
        return;
        }
        sta++;
    }
    pool.query('update xz_order set ? where aid=?',[obj,obj.aid],(err,results)=>{
        // console.log('results: ', results);
        if(err){
            next(err);
            return;
        }
    if(results.changedRows===0){
        res.send({code:201,msg:'修改错误！'});
        return;
    }
    res.send({code:200,msg:'修改成功！'});
    });
    // res.send({code:200,msg:'修改成功！'});
});

// http://127.0.0.1:8080/v1/orders/upload
r.delete('/delete:aid',(req,res,next)=>{
    let id=req.params.aid;
    pool.query("delete from xz_order where aid= ?",[id],(err,results)=>{
        // console.log('results: ', results);
        if(err){
            next(err);
            return;
        }
        if(results.affectedRows===0){
            res.send({code:404,msg:'删除失败!'});
            return;
        }else{
            res.send({code:200,msg:'删除成功！'});
        }
    });

    // res.send({code:200,msg:'删除成功'});
});

// http://127.0.0.1:8080/v1/orders/list
r.get('/list',(req,res,next)=>{

    pool.query('select * from xz_order',(err,results)=>{
        if(err){
            next(err);
            return;
        }
        console.log(results);
        res.send(results);
    });
    // res.send({code:200,msg:'查询成功'})
});

module.exports=r;